#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <string.h>
#include <log.h>
#include <timer.h>

#include "scu.h"

#define READERS 1

scu_buf_t bufb;
int running[READERS];

void *reader(void*);

int main(void)
{
  int i, init;
  pthread_t r[READERS];

  logRegisterThread("main");

  memset(running, 0, READERS*sizeof(int));
  
  bufb = scuBufferCreate(65536, SCU_BUF_MAX_READERS, NULL);

  for (i=0; i < READERS; i++)
    pthread_create(&r[i], NULL, reader, (void*)i);

  do
  {
    init = 1;
    for (i=0; i < READERS; i++)
      init = init * running[i];
  } while (!init);  

  sccTransportCreateReceiver(5745, &bufb);
  scuBufferUnlock(&bufb);

  for (i=0; i < READERS; i++)
    pthread_join(r[i], NULL);

  sleep(1);

  return 0;
}

void *reader(void* id)
{
  char data[65536];
  scu_bufptrid_t r;
  int i=0;
  tmr_t timer = tmrInit();
  
  sprintf(data, "reader%03d", (int)id);
  logRegisterThread(data);

  r = scuBufferAddReader(&bufb);

  running[(int)id] = 1;
  
  tmrStart(&timer);
  for (i=0; i < 250; i++)
  {
    //printf("reader %d iteration %d\n", (int)id, i++);
    //printf("read %d bytes\n", scuBufferRead(&buf, r, data, 512, SCU_BUF_BLOCK));
    scuBufferRead(&bufb, r, data, 65536, SCU_BUF_BLOCK_ALL);
    //usleep(1000000L);
  }
  tmrStop(&timer);

  scuBufferRemoveReference(&bufb);

  printf("Speed was %f MB/s\n", 250.0*65536/tmrGetValueInUs(&timer));

  return NULL;
}
